#include "TcpConnection.h"
#include "EchoServer.h"

#include <iostream>
#include <functional>

using std::bind;
using std::cout;
using std::endl;

MyTask::MyTask(const string &msg, const TcpConnectionPtr &con)
    : _msg(msg), _con(con)
{
}

void MyTask::process()
{
    // 处理业务逻辑
    _con->sendInLoop(_msg);
}

SearchServer::SearchServer(size_t threadNum, size_t queSize, const string &ip, unsigned short port)
    : _pool(threadNum, queSize), _server(ip, port)
{
}

SearchServer::~SearchServer()
{
}

// 服务器的启动与停止
void SearchServer::start()
{
    _pool.start();

    // 三个回调放在此处进行注册
    using namespace std::placeholders;
    _server.setAllCallback(
        bind(&SearchServer::onNewConnection, this, _1),
        bind(&SearchServer::onMessage, this, _1),
        bind(&SearchServer::onClose, this, _1));
    _server.start();
}

void SearchServer::stop()
{
    _pool.stop();
    _server.stop();
}

// 三个回调
void SearchServer::onNewConnection(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has connected!!!" << endl;
}

void SearchServer::onMessage(const TcpConnectionPtr &con)
{
    string msg = con->receive();
    cout << ">>recv msg from client : " << msg << endl;

    MyTask task(msg, con);

    _pool.addTask(bind(&MyTask::process, task));
}

void SearchServer::onClose(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has closed!!!" << endl;
}